package cn.com.cdb.ldms.exception.handler;

import cn.com.cdb.ldms.base.Result;
import com.google.common.net.MediaType;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class CustomErrorControllerHandler implements ErrorController {
    @GetMapping(value = "/favicon.ico")
    public ResponseEntity<Resource> getFavicon() {
        Resource resource = new ClassPathResource("resources/favicon.ico");
        if (!resource.exists()) {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok()
                .cacheControl(CacheControl.noCache())
                .header(HttpHeaders.CONTENT_TYPE, MediaType.ICO.type())
                .body(resource);
    }

    @RequestMapping("/error")
    public ResponseEntity<Result> handleError(HttpServletRequest request) {
        final HttpStatus status = getStatus(request);
        return new ResponseEntity<>(Result.fail(status.value() + "000", "请求的资源不存在"), status);
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}